
<template>
  <div class="affix">
    <el-button type="primary" @click="showCorrect = !showCorrect">{{ `${showCorrect ? '隐藏' : '显示'}` }} 参考解析</el-button>
    <el-button v-if="collectIdList.length" type="primary"  @click="openCollectHandle"> 我的 ✿ </el-button>
  </div>
  <div v-for="( item, index) in list" :ref="`item${index}`" >
    <!-- <h2><SupportIcon /> 单选题</h2> -->
    <RadioGroup v-if="item.question_style === 1" collectShow :collectIdList="collectIdList" @addCollect="addCollect" :showCorrect="showCorrect" :item="item" :index="index" @change="(value) => radioChange(value, item)"/>

    <!-- <h2><SupportIcon /> 多选题</h2> -->
    <CheckboxGroup v-else-if="item.question_style === 3"  collectShow :collectIdList="collectIdList" @addCollect="addCollect" :item="item" :index="index" @change="(value) => checkboxChange(value, item)"/>
    
      <!-- 选词填空/阅读选择 -->
    <div v-else-if="item.question_style === 6" class="margin-b-15">
      <p style="margin-bottom: 10px;">{{index+1}}.{{ item.content }}</p>
      <div v-for="(c, i) in item.child">
        <RadioGroup v-if="c.question_style === 1"  collectShow :collectIdList="collectIdList" @addCollect="addCollect" :showCorrect="showCorrect" :item="c" :index="i" @change="(value) => radioChange(value, c)"/>
        <div v-else>{{ c.title }}（{{item.fraction}}分）<input style="margin-left: 10px;" /></div>
      </div>
      <p v-if="item.child[0].question_style === 4 && showCorrect">参考解析：<span>{{item.child.map((c: any) => c.correct_item).join()}}</span></p>
    </div>  

    <!-- <h2><SupportIcon /> 简答题</h2> -->
    <div v-else class="margin-b-15">
      <p class="font-700">{{ index+1 }}.{{item.title}}（{{item.fraction}}分）
        <span :class="['collect-icon', collectIdList.includes(item.question_id) ? 'red' : '']" 
          title="收藏" 
          @click="addCollect(item.question_id)"
          >✿</span>
      </p>
      <p>参考解析：<span>{{item.analysis}}</span>
      </p>
    </div>

  </div>

    <br/>
    <div class="save-btn">
      <el-button type="success" @click="HandleRest(3)"> 重 做 </el-button>
      <el-button type="primary" @click="saveHandle"> 提 交 </el-button>
    </div>
    

    <!-- <el-dialog v-model="dialogVisible" title="错题再练" fullscreen >
      <template v-for="( item, index) in dialogList" >
        <RadioGroup v-if="item.question_style === 1" :item="item" :index="index" @change="(value) => radioChange(value, item)"/>
        <CheckboxGroup v-else-if="item.question_style === 3" :item="item" :index="index" @change="(value) => checkboxChange(value, item)"/>
      </template>
      <div class="save-btn"><el-button type="success" @click="HandleRest(2)"> 重 做 </el-button></div>
      <div class="save-btn"><el-button type="primary" @click="dialogVisible = false"> 返 回 </el-button></div>
    </el-dialog> -->
    <div v-if="dialogVisible">
      <Dialog v-model="dialogVisible" :list="dialogList" :collectIdList="collectIdList" :dialogType="dialogType" @addCollect="addCollect"/>
    </div>
  
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance } from "vue";
import { useRoute } from 'vue-router';
import RadioGroup from "./components/RadioGroup.vue";
import CheckboxGroup from "./components/CheckboxGroup.vue";
import Dialog from "./components/Dialog.vue";
import getData from '@/data/util.ts'

const route = useRoute();

import {
  ElButton,
  ElDialog,
  ElMessage,
  ElAffix
} from "element-plus";

const instance = (getCurrentInstance()) as any; // instance 相当于以前的 `this`

const props = defineProps({
  data: {
    type: Array as any,
    default: () => []
  }
})

const pageName = ref<any>(route.name)

let list =  ref<any[]>([])

let showCorrect = ref<boolean>(true) //显示参考答案

// 错题列表
let errorIds = ref<string[]>([])
// 收藏列表ID
let collectIdList = ref<string[]>([])
//弹窗列表
let dialogType = ref< 0 | 1 | 2>(0) // 0默认 1错误  2收藏
let dialogList = ref<any[]>([])
let dialogVisible = ref<boolean>(false)

onMounted(() => { 
  list.value = getData(props.data)

  let cIds = localStorage.getItem(pageName.value) 
  if (cIds) { 
    collectIdList.value = JSON.parse(cIds)
  }
})

function checkboxChange(value: [], item: any) { 
  item.error = value.sort().join() !== item.correct_item.sort().join()
  //错题加入错题列表
  item.error && !errorIds.value.includes(item.question_id) && errorIds.value.push(item.question_id)
}
function radioChange(value: string, item: any) { 
  item.error = value && item.correct_item !== item.val
  //错题加入错题列表
  item.error && !errorIds.value.includes(item.question_id) && errorIds.value.push(item.question_id)
}

function saveHandle() { 
  const emptyIndex = verifyHasEmpty(list.value)
  if (emptyIndex > -1) { 
    scrollIntoRef(emptyIndex) // 滚动到空题
    return false
  }
  dialogType.value = 1
  dialogList.value = []
  getData(props.data).forEach(item => {
    if (errorIds.value.includes(item.question_id)) { 
      dialogList.value.push(item)
    }
    if (item.child && item.child.length) { 
      item.child.forEach((c: any) => { 
        if (errorIds.value.includes(c.question_id)) { 
          dialogList.value.push(c)
        }
      })
    }
  })
  dialogVisible.value = true
}
function scrollIntoRef(index: number) {
  instance.refs[`item${index}`][0].scrollIntoView({ behavior: 'smooth' });
}

// 校验是否存在空题
function verifyHasEmpty(list: any) {
  const empty = list.findIndex((item: any) => { 
    if (
      (item.question_style === 3 && item.val.length === 0) || //多选
      (item.question_style === 1 && !item.val)  // 单选
    ){ 
      return true
    }
  })
  if (empty > -1) { 
    ElMessage({
      message: '存在空题',
      type: 'error',
      plain: true,
    })
    return empty
  }
  return -1
}

type ResetType = 2 | 3 // 2 错题重置   3 列表重置
function HandleRest(type: ResetType) {
  if (type === 3) { 
    location.reload();
  }
  const resetList = type === 2 ? dialogList : list
    resetList.value.forEach(item => { 
      item.val = item.question_style === 3 ? [] : ''
      item.error = false
    })

  scrollIntoRef(0)
}

//加入收藏列表
function addCollect(id: string) { 
  if (collectIdList.value.includes(id)) {
    collectIdList.value = collectIdList.value.filter(cid => cid !== id)
  } else { 
    collectIdList.value.push(id)
  }

  localStorage.setItem(pageName.value, JSON.stringify(collectIdList.value))
}

//打开收藏列表
function openCollectHandle() {
  dialogList.value = []
  dialogType.value = 2
  getData(props.data).forEach(item => {
    if (collectIdList.value.includes(item.question_id)) { 
      dialogList.value.push(item)
    }
    if (item.child && item.child.length) { 
      item.child.forEach((c: any) => { 
        if (collectIdList.value.includes(c.question_id)) { 
          dialogList.value.push(c)
        }
      })
    }
  })
  dialogVisible.value = true
}

</script>


<style scoped>
h4{
  font-weight: 700;
}
</style>
